package com.uduew.sjd.ui.home

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import com.uduew.sjd.BR
import com.uduew.sjd.R
import com.uduew.sjd.api.AllLoanOrdersApi
import com.uduew.sjd.api.FormListApi
import com.uduew.sjd.api.ProductHomeApi.ResProductHomeBean
import com.uduew.sjd.api.ProductInfoApi
import com.uduew.sjd.bean.HttpBean
import com.uduew.sjd.config.AppConfig
import com.uduew.sjd.message.Messages
import com.uduew.sjd.message.PageMessenger
import com.uduew.sjd.net.DataResult
import com.uduew.sjd.request.FormRequester
import com.uduew.sjd.request.ProductHomeRequester
import com.uduew.sjd.request.ProductInfoRequester
import com.uduew.sjd.request.RepaymentRequester
import com.uduew.sjd.ui.adapter.HomeProductAdapter
import com.uduew.sjd.ui.base.BaseFragment
import com.uduew.sjd.ui.base.StateHolder
import com.uduew.sjd.ui.form.FormActivity
import com.uduew.sjd.ui.login.LoginActivity
import com.uduew.sjd.utils.MainHandler
import com.uduew.sjd.utils.ToastUtils
import com.uduew.sjd.utils.Utils
import com.kongzue.dialogx.dialogs.PopTip
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kunminx.architecture.ui.page.DataBindingConfig
import com.kunminx.architecture.ui.state.State
import com.uduew.sjd.config.Const
import com.uduew.sjd.databinding.FragmentHomeBinding
import com.uduew.sjd.utils.SpannableUtils
import com.uduew.utils.NetworkUtils

class HomeFragment : BaseFragment() {

    lateinit var mState: HomeStates
    private lateinit var mFormRequester: FormRequester
    private lateinit var mProductHomeRequester: ProductHomeRequester
    private lateinit var mMessenger: PageMessenger

    private lateinit var mAdapter: HomeProductAdapter
    private lateinit var mProductInfoRequester: ProductInfoRequester
    private lateinit var mRepaymentRequester: RepaymentRequester
    override fun initViewModel() {
        mMessenger = getApplicationScopeViewModel(PageMessenger::class.java)
        mState = getFragmentScopeViewModel(HomeStates::class.java)
        mProductHomeRequester =
            getFragmentScopeViewModel(ProductHomeRequester::class.java)
        mFormRequester = getFragmentScopeViewModel(FormRequester::class.java)
        mProductInfoRequester =
            getFragmentScopeViewModel(ProductInfoRequester::class.java)
        mRepaymentRequester = getActivityScopeViewModel(RepaymentRequester::class.java)
    }

    private fun requestData() {
        requestRepayment()
        requestProductInfo()
    }

    private fun requestFormData() {
        if (!AppConfig.isLogin) {
            mState.productCount.set(1)
            mState.formCount.set(5)
            mState.refreshState.set(false)
            return
        }
        mFormRequester.request(viewLifecycleOwner, Const.THEOLOGIST)
    }

    private fun requestProductInfo() {
        mProductInfoRequester.request(this)
    }

    private fun requestRepayment() {
        val debrief = ArrayList<String>()
        debrief.add("firemen") //待还
        debrief.add("underwent") //审批中
        debrief.add("breeks") //逾期
        mRepaymentRequester.request(
            viewLifecycleOwner,
            "", debrief,
            1, 10
        )
    }

    var isLoanFragmentClose = true

    private fun gotoLoanFragment() {
        if (!Utils.checkDebounce()) return
//        val bundle = Bundle()
//        if (!isLoanFragmentClose) {
//            return
//        }
//        nav().navigate(R.id.action_navigation_main_to_loan_fragment, bundle).also {
//            isLoanFragmentClose = false
//        }
        mMessenger.input(Messages(Messages.EVENT_INIT_MAIN, "1", ""))
    }

    private fun gotoOrderStateFragment() {
        if (!Utils.checkDebounce()) return
//        val bundle = Bundle()
//        if (mState.shouldViewOrder) {
//            bundle.putBoolean("shouldViewOrder", true)
//            nav().navigate(
//                R.id.action_navigation_main_to_loan_detail_fragment, bundle
//            )
//            mState.shouldViewOrder = false
//        }
        mMessenger.input(Messages(Messages.EVENT_INIT_MAIN, "2", ""))
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        isConnected()
        (getBinding() as FragmentHomeBinding).apply {
            state.onRefresh {
                MainHandler.postDelay(3000) {
                    isConnected()
                }
            }
        }
        mMessenger.output(this) { messages ->

            if (messages.eventId == Messages.EVENT_APPLY_SUCCESS || messages.eventId == Messages.EVENT_LOGIN_SUCCESS || messages.eventId == Messages.EVENT_REFRESH_HOME) {
                refreshData()
            }
            if (messages.eventId == Messages.EVENT_LOGIN_SUCCESS) {
                if (!AppConfig.isFirstRegister) {
                    Intent(requireContext(), FormActivity::class.java).apply {
                        startActivity(this)
                    }
                    AppConfig.isFirstRegister = true
                }
            }
            if (messages.eventId == Messages.EVENT_CERTIFICATION_SUCCESS) {
//                gotoLoanFragment()
            }
            if (messages.eventId == Messages.EVENT_UPDATE_PRODUCT) {
                mAdapter.notifyDataSetChanged()
                val selectedItems = mAdapter.currentList.filter { it.isSelected }
                mState.selectList.set(selectedItems as ArrayList<ProductInfoApi.ThoroughBean>)
            }
            if (messages.eventId == Messages.EVENT_LOAN_FRAGMENT_CLOSE) {
                isLoanFragmentClose = true
            }
        }
        mFormRequester.result.observe(viewLifecycleOwner) { dataResult: DataResult<HttpBean<FormListApi.FormListBean>> ->
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            mState.formCount.set(dataResult.result.data?.mothery?.size ?: 0)
            AppConfig.unfinishedFormCount = dataResult.result.data?.mothery?.size ?: 0
            if (mState.formCount.get() == 0) {
                requestData()
            } else {
                MainHandler.postDelay(800) {
                    mState.refreshState.set(false)
                    WaitDialog.dismiss()
                }
            }
        }

        mRepaymentRequester.result.observe(viewLifecycleOwner) { dataResult: DataResult<AllLoanOrdersApi.ResAllLoanOrdersBean> ->
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            dataResult.result.let {
                mState.orderList = it.mamaguy.thorough
                var repayList = it.mamaguy.thorough.filter {
                    it.phylogenic == "firemen" || it.phylogenic == "breeks"
                }
                var reviewList = it.mamaguy.thorough.filter {
                    it.phylogenic == "underwent"
                }
                mState.repayList.set(repayList.size)
                mState.reviewList.set(reviewList.size)


                mState.reviewOrderCount.set(getString(R.string.you_exist) + reviewList.size + getString(
                    R.string.orders_awaiting_review
                ))
                mState.repayOrderCount.set(
                    getString(R.string.you_exist) + repayList.size
                            + getString(R.string.an_order_pending_repayment)
                )
                val totalRepayAmountWait = reviewList.sumOf { it.nuciform.toDouble() }
                val amountFormatWait = SpannableUtils.getDoubleFormat(totalRepayAmountWait)
                mState.repayAmountWait.set("${Const.CURRENCY_SYMBOL}$amountFormatWait")
                val totalRepayAmountSuccess = repayList.sumOf { it.tubulure.toDouble() }
                val amountFormatSuccess = SpannableUtils.getDoubleFormat(totalRepayAmountSuccess)
                mState.repayAmountSuccess.set("${Const.CURRENCY_SYMBOL}$amountFormatSuccess")
            }
        }


        mProductInfoRequester.result.observe(viewLifecycleOwner)
        { dataResult: DataResult<ProductInfoApi.ResProductInfoBean> ->
            WaitDialog.dismiss()
            mState.refreshState.set(false)
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            dataResult.result.let {
                if (it != null) {
                    it.mamaguy.thorough.take(5).forEach { item ->
                        item.isSelected = true
                    }
                    mState.list.set(it.mamaguy.thorough)
                    mState.productCount.set(it.paillette.speedwell)
                    val selectedItems = it.mamaguy.thorough.filter { it.isSelected }
                    mState.selectList.set(selectedItems as ArrayList<ProductInfoApi.ThoroughBean>)
                    if (it.paillette.wottest == 0) {   //用户订单数==0时，展示试算；
                        gotoLoanFragment()
                    } else if (it.paillette.speedwell == 1) { //用户产品数=1时（单产品）:
                        if (it.mamaguy.thorough.isNotEmpty()) { //产品列表size>0,展示试算页面
                            gotoLoanFragment()
                        } else { //展示订单状态页面。
                            mState.shouldViewOrder = true
                            gotoOrderStateFragment()
                        }
                    }
                    if (it.mamaguy.thorough.isEmpty()) {
                        mState.productCount.set(0)
                    }
                }
            }
        }

        mProductHomeRequester.result.observe(viewLifecycleOwner)
        { dataResult: DataResult<HttpBean<ResProductHomeBean>> ->
            WaitDialog.dismiss()
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            dataResult.result.data.let {
                if (it != null) {
                    val backhouse = it.backhouse?.takeIf { str -> str.contains("-") }
                        ?.split("-")
                        ?.getOrNull(1)
                        ?.trim()
                        ?: it.backhouse?.replace(",", "") // 处理无分隔符的情况
                    mState.backhouse.set(backhouse.toString())
                    mState.icw.set(String.format(getString(R.string.unit), it.icw))
                }
            }
        }
        WaitDialog.show(getString(R.string.loading))
        mProductHomeRequester.request(this)
        refreshData()
    }

    override fun onPause() {
        super.onPause()
        WaitDialog.dismiss()
    }


    private fun isConnected() {
        if (NetworkUtils.isConnected()) {
            (getBinding() as FragmentHomeBinding).apply {
                state.showContent()
                mProductHomeRequester.request(this@HomeFragment)
                refreshData()
            }
        } else {
            (getBinding() as FragmentHomeBinding).apply {
                state.showError()
            }
        }
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        mAdapter = HomeProductAdapter(requireContext())
        mAdapter.setOnItemClickListener { id, item, position ->
            item.isSelected = !item.isSelected;
            mAdapter.notifyItemChanged(position);
            val selectedItems = mAdapter.currentList.filter { it.isSelected }
            mState.selectList.set(selectedItems as ArrayList<ProductInfoApi.ThoroughBean>)
        }

        return DataBindingConfig(R.layout.fragment_home, BR.vm, mState)
            .addBindingParam(BR.adapter, mAdapter)
            .addBindingParam(BR.click, ClickProxy())
            .addBindingParam(BR.refreshListener, ListenerRefreshHandler())
    }

    inner class ListenerRefreshHandler : OnRefreshListener {
        override fun onRefresh() {
            refreshData()
        }
    }

    private fun refreshData() {
        mMessenger.input(Messages(Messages.EVENT_UPDATE_SUCCESS))
        mState.refreshState.set(true)
        requestFormData()
    }


    class HomeStates : StateHolder() {
        val text: State<String> = State("home")
        val numberOfColumns: State<Int> = State(2)
        val list: State<ArrayList<ProductInfoApi.ThoroughBean>> =
            State<ArrayList<ProductInfoApi.ThoroughBean>>(ArrayList<ProductInfoApi.ThoroughBean>())
        val selectList: State<ArrayList<ProductInfoApi.ThoroughBean>> =
            State<ArrayList<ProductInfoApi.ThoroughBean>>(ArrayList<ProductInfoApi.ThoroughBean>())
        val formCount: State<Int> = State(5)
        val repayList: State<Int> = State(0)
        var orderList: ArrayList<AllLoanOrdersApi.ResAllLoanOrdersBean.MamaguyBean.ThoroughBean> =
            ArrayList<AllLoanOrdersApi.ResAllLoanOrdersBean.MamaguyBean.ThoroughBean>()

        val reviewList: State<Int> = State(0)

        val productCount: State<Int> = State(1)
        val backhouse: State<String> = State("")
        val icw: State<String> = State("")
        val refreshState: State<Boolean> = State(true)
        val refreshEnabled: State<Boolean> = State(true)

        var shouldViewOrder: Boolean = false

        val reviewOrderCount: State<String> = State("")
        val repayOrderCount: State<String> = State("")
        val repayAmountWait: State<String> = State("")
        val repayAmountSuccess: State<String> = State("")
    }


    open inner class ClickProxy {
        fun refresh() {
            refreshData()
        }

        fun orderRepayDetail() {
            if (!Utils.checkDebounce()) return
            val bundle = Bundle()
            bundle.putInt("type", 2)
            nav().navigate(R.id.action_navigation_main_to_all_loan_orders_fragment, bundle)
        }

        fun orderReviewDetail() {
            if (!Utils.checkDebounce()) return
            val bundle = Bundle()
            bundle.putInt("type", 1)
            nav().navigate(R.id.action_navigation_main_to_all_loan_orders_fragment, bundle)
        }

        fun checkLogin() {
            if (!Utils.checkDebounce()) return
            if (!AppConfig.isLogin) {
                requireContext().startActivity(Intent(context, LoginActivity::class.java))
                return
            }
        }

        fun nowApply() {
            if (!Utils.checkDebounce()) return
            if (!AppConfig.isLogin) {
                requireContext().startActivity(Intent(context, LoginActivity::class.java))
                return
            }
            Intent(requireContext(), FormActivity::class.java).apply {
                startActivity(this)
            }
        }

        fun loan() {
            if (!Utils.checkDebounce()) return
            if (!AppConfig.isLogin) {
                requireContext().startActivity(Intent(context, LoginActivity::class.java))
                return
            }
            val bundle = Bundle()
            val selectedItems = mAdapter.currentList.filter { it.isSelected }
            mState.selectList.set(selectedItems as ArrayList<ProductInfoApi.ThoroughBean>)
            val list = mState.selectList.get()
            if (list.isNullOrEmpty()) {
                PopTip.show("请选择产品").iconWarning()
                return
            }
            bundle.putParcelableArrayList("product", list)
            nav().navigate(R.id.action_navigation_main_to_loan_fragment, bundle)
        }
    }

}